package common.web.action;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;

import common.log.util.LogModule;
import common.log.util.LogType;
import common.log.vo.WebLog;
import common.rbac.po.User;
import common.rbac.po.UserGroup;
import common.rbac.po.UserRole;
import common.util.JSONUtils;
import common.web.vo.Result;

@SuppressWarnings("deprecation")
@Controller
@RequestMapping("/system/user")
public class UserAction extends CommonAction {

	@Autowired(required = false)
	PasswordEncoder encoder;

	@RequestMapping("/view/{id}")
	@ResponseBody
	public Result view(@PathVariable String id) {
		User user = this.baseService.get(User.class, id);
		if (null == user) {
			return Result.fail("用户不存在");
		}
		Result res = Result.createResult(user);

		UserRole ur = new UserRole();
		ur.setUserId(user.getId());
		res.addMap("roles", baseService.find("select r from Role r, UserRole su where r.id = su.roleId and userId = ?",
				new Object[] { id }));
		return res;
	}

	@RequestMapping("/roles")
	@ResponseBody
	public Result edit(@RequestBody JSONObject json) {
		ArrayList<Object> params = new ArrayList<>();
		String hql = "from Role ";
		return Result.createResult(baseService.find(hql, params.toArray()));
	}

	@RequestMapping("/list")
	@ResponseBody
	public Result list(@RequestBody JSONObject json) {
		List<Object> params = new ArrayList<>();
		Map<String, Class<?>> clazzMap = new HashMap<String, Class<?>>();
		clazzMap.put("u", User.class);
		String hql = "from User u where " + super.handleFilter(clazzMap, json, params);
		String countHql = "select count(*) " + hql;
		hql += super.handleSort(json);
		return Result.createPageResult(
				baseService.find(hql, countHql, super.getPageNumber(json), super.getPageSize(json), params.toArray()));
	}

	@RequestMapping("/{editType}")
	@ResponseBody
	public Result save(@PathVariable String editType, @RequestBody JSONObject json) {
		User user = JSONUtils.toJavaObject(json.getJSONObject("entity"), User.class);
		List<UserGroup> ugs = JSONUtils.toJavaObject(json.getJSONArray("groups"), UserGroup.class);
		List<UserRole> urs = JSONUtils.toJavaObject(json.getJSONArray("roles"), UserRole.class);

		if (null != user) {
			WebLog log = new WebLog(LogModule.USER, LogType.ADD, "操作失败");
			if ("update".equals(editType)) {
				log.setType(LogType.UPDATE);
			}
			try {
				List<Object> saves = new ArrayList<Object>();
				saves.addAll(ugs);
				saves.addAll(urs);

				List<Object> deletes = new ArrayList<>();

				if ("update".equals(editType)) {
					super.setCommonUpdateInfo(user);
					UserGroup ug = new UserGroup();
					ug.setUserId(user.getId());
					UserRole ur = new UserRole();
					ur.setUserId(user.getId());
					// 删除关联部分
					deletes.addAll(baseService.findByExample(ug));
					deletes.addAll(baseService.findByExample(ur));

					baseService.dbOperation(saves.toArray(), new Object[] { user }, deletes.toArray());
					log.setSuccess(MessageFormat.format("修改用户[{0}]成功!", user.getName()));
				} else if ("add".equals(editType)) {
					super.setCommonSaveInfo(user);
					for (UserRole urf : urs) {
						urf.setUserId(user.getId());
					}
					 for (UserGroup ugf : ugs) {
					 ugf.setUserId(user.getId());
					 }
					user.setEnabled(true);
					user.setNonLock(true);
					saves.add(user);

					if (null != encoder) {
						user.setPassword(encoder.encodePassword(user.getPassword(), null));
					}
					baseService.dbOperation(saves.toArray(), null, null);
					log.setSuccess(MessageFormat.format("新增用户[{0}]成功!", user.getName()));
				}
			} catch (Exception e) {
				log.setFail(MessageFormat.format("新增用户[{0}]失败!", user.getName()));
				logger.error("", e);

				return Result.fail("数据错误，请刷新后重试");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("数据错误，请刷新后重试");
		}
		return Result.SUCCESS;
	}

	@RequestMapping("/delete/{id}")
	@ResponseBody
	public Result delete(@PathVariable String id) {
		User load = baseService.get(User.class, id);
		if (null != load) {
			WebLog log = new WebLog(LogModule.USER, LogType.DELETE, "操作失败");
			try {
				List<Object> deletes = new ArrayList<>();

				deletes.add(load);

				// 关联的查询出来一起删除
				 UserGroup ug = new UserGroup();
				 ug.setUserId(load.getId());
				UserRole ur = new UserRole();
				ur.setUserId(load.getId());

				// 删除关联部分
				deletes.addAll(baseService.findByExample(ug));
				deletes.addAll(baseService.findByExample(ur));

				baseService.delete(deletes.toArray());

				// 日志
				log.setSuccess(MessageFormat.format("删除用户[{0}]成功!", load.getName()));
			} catch (Exception e) {
				log.setFail(MessageFormat.format("删除用户[{0}]失败!", load.getName()));
				logger.error("", e);

				return Result.fail("删除失败");
			} finally {
				logService.saveLog(log);
			}
		} else {
			return Result.fail("用户不存在");
		}
		return Result.SUCCESS;
	}

}
